import userDao from "../Dao/user.js";
import {checkMobile, httpResult} from "../utils/utils.js";
import companyUserDao from "../Dao/company_user.js";
import {checkUserExist, queryCheckId} from "./utils.js";
import companyDao from "../Dao/company.js";

// 同步注册信息
export const syncRegister = async (req, res) => {
  let {id, email, invitation_code, inviter_id, user_name} = req.body;
  // console.log(id, email, invitation_code, inviter_id, user_name, 'syncRegister');
  if (!id || !email || !invitation_code || !inviter_id || !user_name) {
    throw new Error('注册数据不正确');
  }
  // 添加用户为个人用户
  await userDao.addUser(id, user_name, email, invitation_code, inviter_id);
  res.json(httpResult.success({result: true}));
};

// 检查注册信息
export const checkRegister = async (req, res) => {
  let {id} = req.body;
  await queryCheckId(id);
  let result = await userDao.findUserLock(id);
  if (result) {
    res.json(httpResult.success({result: true}));
    return;
  }
  res.json(httpResult.success({result: false}));
};

// 登录获取用户信息 个人信息和公司信息 后续查询可以使用数组一次性查完42行
export const getUserInfo = async (req, res) => {
  let {id} = req.body;
  await queryCheckId(id);
  // 获取用户个人信息
  let userInfo = await userDao.findUserLock(id);
  checkUserExist(userInfo);
  // 获取用户公司信息
  let companyInfo = await companyUserDao.getCompanyListByUserId(id);
  // 获取公司的名称添加进去
  for (let i = 0; i < companyInfo.length; i++) {
    companyInfo[i].companyName = (await companyDao.getCompanyName(companyInfo[i].company_id)).company_name;
  }
  userInfo.companyList = companyInfo;
  userInfo.result = true;
  res.json(httpResult.success(userInfo));
};

// 设置用户手机号
export const setUserMobile = async (req, res) => {
  let {id, mobile} = req.body;
  if(!checkMobile(mobile)) {
    throw new Error('手机号格式不正确');
  }
  await queryCheckId(id);
  let mobileUser = await userDao.findUserByNameOrEmailOrMobile(null, null, mobile);
  if(mobileUser) {
    throw new Error('手机号已存在');
  }
  await userDao.updateUserMobile(id, mobile);
  res.json(httpResult.success({result: true}));
};


